<?php

namespace App\Http\Controllers\BaseData;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // dd(User::where(['id' => 2])->first()->getRoles());
        if (post("?")) {
            return (User::search(post("search"))->relatedJoin()->getGrid());
        } else {
            return view('BaseData.UserController.index', F());
        }
    }

    public function add()
    {
        // dd(Menu::treeGrid()->toArray());
        if (post("?")) {
            $data = post("data");
            try {
                begin();
                $gdata = User::create(unsetNull($data));
                $gdata->saveitems(json_decode(post('items'), true));
                commit();
            } catch (\Exception $e) {
                rollback();
                return error($e->getMessage());
            }

            return success("保存成功！");
        } else {
            $param = F('edit');
            return view('BaseData.UserController.edit',  $param);
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit()
    {
        $id = get("id");
        $gdata = User::where("id", $id)->first();
        // dd(Menu::treeGrid()->toArray());
        if (post("?")) {
            $data = post("data");
            try {
                begin();
                $gdata->update(unsetNull($data));
                $gdata->saveitems(json_decode(post('items'), true));
                commit();
            } catch (\Exception $e) {
                rollback();
                return error($e->getMessage());
            }

            return success("保存成功！");
        } else {
            $param = F('edit');
            $param['gdata'] = $gdata;
            $param['items'] = $gdata->rolesList()->relatedJoin()->get();
            return view('BaseData.UserController.edit',  $param);
        }
    }

    public function delete()
    {
        begin();
        $ids = request()->post('ids');;
        // Category::whereIn("id", $ids)->delete();
        foreach (User::whereIn("id", $ids)->get() as  $k => $v) {
            //盘点能否删除
            $v->delete();
        }
        commit();
        return success("删除成功！");
    }
}
